<template>
  <div class="auth-container">
    <!-- 模式切换 -->
    <div class="mode-tabs">
      <div 
        :class="['tab-item', { 'active': activeMode === 'login' }]"
        @click="switchMode('login')"
      >
        登录
      </div>
      <div 
        :class="['tab-item', { 'active': activeMode === 'register' }]"
        @click="switchMode('register')"
      >
        注册
      </div>
      
    </div>

    <!-- 登录表单 -->
    <transition name="el-zoom-in-top">
      <el-form
        v-if="activeMode === 'login'"
        :model="loginForm"
        :rules="loginRules"
        ref="loginForm"
        label-width="0"
        class="custom-form"
      >
        <div class="login-type">
          <el-radio-group v-model="loginType" size="medium">
            <el-radio-button label="account">
              <i class="el-icon-user"></i> 账号登录
            </el-radio-button>
            <el-radio-button label="sms">
              <i class="el-icon-mobile-phone"></i> 验证码登录
            </el-radio-button>
          </el-radio-group>
        </div>

        <!-- 账号登录 -->
        <template v-if="loginType === 'account'">
          <el-form-item prop="phonenumber">
            <el-input
              v-model="loginForm.phonenumber"
              placeholder="请输入手机号"
              prefix-icon="el-icon-user"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="el-icon-lock"
              show-password
            ></el-input>
          </el-form-item>
        </template>

        <!-- 验证码登录 -->
        <template v-else>
          <el-form-item prop="phone">
            <el-input
              v-model="loginForm.phone"
              placeholder="请输入手机号"
              prefix-icon="el-icon-mobile-phone"
            ></el-input>
          </el-form-item>
          <el-form-item prop="smsCode">
            <div class="sms-input">
              <el-input
                v-model="loginForm.smsCode"
                placeholder="请输入验证码"
                prefix-icon="el-icon-message"
              ></el-input>
              <el-button
                class="sms-btn"
                :disabled="smsLoginCountdown > 0"
                @click="sendLoginSms"
              >
                {{ smsLoginCountdown ? `${smsLoginCountdown}秒后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
        </template>

        <el-button
          type="primary"
          class="submit-btn"
          @click="handleLogin"
        >
          立即登录
        </el-button>
      </el-form>
    </transition>

    <!-- 注册表单 -->
    <transition name="el-zoom-in-top">
      <el-form
        v-if="activeMode === 'register'"
        :model="registerForm"
        :rules="registerRules"
        ref="registerForm"
        label-width="0"
        class="custom-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            prefix-icon="el-icon-mobile-phone"
          ></el-input>
        </el-form-item>
        <el-form-item prop="smsCode">
          <div class="sms-input">
            <el-input
              v-model="registerForm.smsCode"
              placeholder="请输入验证码"
              prefix-icon="el-icon-message"
            ></el-input>
            <el-button
              class="sms-btn"
              :disabled="smsRegisterCountdown > 0"
              @click="sendRegisterSms"
            >
              {{ smsRegisterCountdown ? `${smsRegisterCountdown}秒后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
        <el-button
          type="primary"
          class="submit-btn"
          @click="handleRegister"
        >
          立即注册
        </el-button>
      </el-form>
    </transition>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import authApi from '@/api/auth'

export default {
  data() {
    return {
      activeMode: 'login',
      loginType: 'account',
      smsLoginCountdown: 0,
      smsRegisterCountdown:0,
      loginForm: {
        phonenumber: '',
        password: '',
        phone: '',
        smsCode: ''
      },
      registerForm: {
        username: '',
        password: '',
        phone: '',
        smsCode: ''
      },
      loginRules: {
        phonenumber: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在6到16个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        smsCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
        ]
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 16, message: '长度在4到16个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在6到16个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        smsCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
        ]
      }
    }
  },
    methods: {
    startLoginCountdown() {
      this.smsLoginCountdown = 60
      const timer = setInterval(() => {
        this.smsLoginCountdown--
        if (this.smsLoginCountdown <= 0) clearInterval(timer)
      }, 1000)
        },
    startRegisterCountdown() {
      this.smsRegisterCountdown = 60
      const timer = setInterval(() => {
        this.smsRegisterCountdown--
        if (this.smsRegisterCountdown <= 0) clearInterval(timer)
      }, 1000)
        },
        // 发送验证码（统一处理）
    // async sendSmsCode(type) {
    //   try {
    //     const phoneField = type === 'login' ? this.loginForm.phone : this.registerForm.phone
    //     if (!phoneField.match(/^1[3-9]\d{9}$/)) {
    //       return Message.error('请输入正确的手机号')
    //     }

    //     await authApi.sendSmsCode(phoneField, type)
    //     this.startCountdown()
    //     Message.success('验证码已发送')
    //   } catch (error) {
    //     Message.error(error.message || '发送失败')
    //   }
    // },
        async sendLoginSms() {
        try {
            if (!this.loginForm.phone.match(/^1[3-9]\d{9}$/)) {
                return Message.error('请输入正确的手机号')
            }
          this.startLoginCountdown()
           let response
            response = await authApi.sendSmsCode(this.loginForm.phone,'login')
          console.log(response.data)

          if (response.data) {
            if (response.data.success == true) {
              console.log("send sms success")
              Message.success('验证码发送成功')
            } else {
              Message.warning('验证码发送失败:' + response.data.errInfo)
            }
          }else {
            Message.warning('验证码发送失败')
          }
            
        } catch (error) {
            Message.error(error.message || '发送失败')
        }
    },
    async sendRegisterSms() {
        try {
            if (!this.registerForm.phone.match(/^1[3-9]\d{9}$/)) {
                return Message.error('请输入正确的手机号33')
            }
            this.startRegisterCountdown()
            let response
            response = await authApi.sendSmsCode(this.registerForm.phone,'register')
          console.log(response.data)

          if (response.data) {
            if (response.data.success == true) {
              console.log("send sms success")
              Message.success('验证码发送成功')
            } else {
              Message.warning('验证码发送失败:' + response.data.errInfo)
            }
          }else {
            Message.warning('验证码发送失败')
          }
          
            
            

        } catch (error) {
            Message.error(error.message || '发送失败')
        }
    },
    async handleLogin() {
    //   this.$refs.loginForm.validate(valid => {
    //     if (valid) {
    //         // 模拟登录成功
    //         // localStorage.setItem('authToken', 'your_jwt_token')

    //         this.$store.commit('login', '你的token')

    //         // 跳转到目标页面或默认页面
    //         const redirect = this.$route.query.redirect || '/assistant'
    //         this.$router.push(redirect)

    //         this.$message.success('登录成功')
    //     }
    //   })


        try {
            await this.$refs.loginForm.validate()
            console.log('begin login')
            let response
            if (this.loginType === 'account') {
            response = await authApi.loginByAccount({
                phonenumber: this.loginForm.phonenumber,
                password: this.loginForm.password
            })
            } else {
            response = await authApi.loginBySms({
                "phone": this.loginForm.phone,
                "code": this.loginForm.smsCode
            })
            }
          // 跳转逻辑
          response.data.data
            console.log("to response")
          if (response.data) {
            console.log(response.data)
               console.log(response.data.err_no)
            console.log(response.data.success)
            if (response.data.success == true) {
                    console.log("login success")
                    this.$store.commit('login', '你的token')
                    const redirect = this.$route.query.redirect  || '/datadisplay'
                    this.$router.push(redirect)
                    Message.success('登录成功')
            } else {
                  Message.warning('登录失败:' + response.data.errInfo)
                }

            } else {
                Message.warning('登录失败')
            }
            } catch (error) {
                Message.error(error.message || '登录失败')
            }
        },

        
    async handleRegister() {
    //   this.$refs.registerForm.validate(valid => {
    //     if (valid) {
    //       Message.success('注册成功（模拟）')
    //       this.activeMode = 'login'
    //     }
        //   })
            try {
            await this.$refs.registerForm.validate()
            
            let response
            response = await authApi.register({
                "username": this.registerForm.username,
                "password": this.registerForm.password,
                "phone": this.registerForm.phone,
                "code": this.registerForm.smsCode
            })
              if (response.data) {
                if (response.data.success == true) {
                  console.log("register success")
                Message.success('注册成功')
                this.activeMode = 'login'
                } else {
                Message.warning('注册失败:' + response.data.errInfo)
              }

            } else {
                Message.warning('注册失败')
            }

      } catch (error) {
        Message.warning(error.message || '注册失败')
      }
    },
    switchMode(mode) {
      this.activeMode = mode
    }
  }
}
</script>

<style scoped>
.auth-container {
  max-width: 420px;
  margin: 40px auto;
  padding: 30px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0,0,0,0.08);
}

.mode-tabs {
  display: flex;
  margin-bottom: 30px;
  border-bottom: 2px solid #ebeef5;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 15px;
  cursor: pointer;
  color: #909399;
  transition: all 0.3s;
  font-size: 16px;
  position: relative;
}

.tab-item.active {
  color: #409EFF;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  right: 0;
  height: 2px;
  background: #409EFF;
}

.custom-form {
  padding: 0 20px;
}

.login-type {
  margin-bottom: 25px;
}

.sms-input {
  display: flex;
  gap: 10px;
}

.sms-btn {
  flex-shrink: 0;
  width: 120px;
}

.submit-btn {
  width: 100%;
  margin-top: 20px;
  height: 44px;
  font-size: 16px;
  letter-spacing: 2px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-input__prefix i {
  color: #c0c4cc;
  font-size: 16px;
}

.footer {
    position: fixed;
    bottom: 10% -10px;
    left: 50%;
    transform: translateX(-50%);
    font-size: 12px;
    z-index: 1000;
    background: rgba(255, 255, 255, 0.8);
    padding: 2px 8px;
    border-radius: 4px;
}
.footer2 {
    position: fixed;
    bottom: 60px;
    left: 50%;
    transform: translateX(-50%);
    font-size: 12px;
    z-index: 1000;
    background: rgba(255, 255, 255, 0.8);
    padding: 2px 8px;
    border-radius: 4px;
}
</style>
